package com.lora.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;

@Component
@EnableScheduling
public class FfmepgUtil {
    Logger logger= LoggerFactory.getLogger(FfmepgUtil.class);
    @Async
    public void startFfm(String eid,String rstpUrl,String path){
        List<String> commend = new ArrayList<String>();
        commend.add("ffmpeg");
        commend.add("-i");
        commend.add(rstpUrl);
        commend.add("-c");
        commend.add("copy");
        commend.add("-f");
        commend.add("hls");
        commend.add("-hls_time");
        commend.add("2.0");
        commend.add("-hls_list_size");
        commend.add("0");
        commend.add("-hls_wrap");
        commend.add("15");
        commend.add(path+File.separator+eid.substring(eid.lastIndexOf(".")+1)+".m3u8");

        logger.info("推流开始"+commend.toString());
        try {
            Process builder = new ProcessBuilder().command(commend).start();
            MapUtil.put(eid,builder);
            new PrintStream(builder.getErrorStream()).start();
            new PrintStream(builder.getInputStream()).start();
            builder.waitFor();
            return;
        } catch (Exception e) {
            logger.info("推流失败"+e.getLocalizedMessage());
        }
    }

    class PrintStream extends Thread{
        InputStream __is = null;
        public PrintStream(java.io.InputStream is){
            __is=is;
        }
        public void run(){
            try{
                while(this != null){
                    int _ch = __is.read();
                    if(_ch != -1){
                        char ch = (char) _ch;
                    }
                    else break;
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
